package com.example.AoUserApp.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:xec
 * @date:2022/9/7 17:55
 **/
public class LogListController {

    public AnchorPane root;
    @FXML
    private TextField pathTF;
    @FXML
    private ListView LogLV;

    /**
     * 日志窗口选择文件夹文本框点击事件
     */
    @FXML
    protected void OnPathMouseClick(){
        DirectoryChooser directoryChooser=new DirectoryChooser();
        Stage stage = (Stage) root.getScene().getWindow();
        File file = directoryChooser.showDialog(stage);
        if (file!=null){
            String path = file.getPath();//选择的文件夹路径
            pathTF.setText(path);
        }
    }
    @FXML
    private Button setUpBT;

    /**
     * 日志窗口设置按钮点击事件
     */
    @FXML
    protected void OnSetUpBtAction(){
        String pathTFTrim = pathTF.getText().trim();
        if (pathTFTrim!=null&&pathTFTrim!=""){
            // 从文件中获取存储地址
            Resource resource = new ClassPathResource("logStorageAddress.txt");
            try {
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resource.getFile())));
                bufferedWriter.write(pathTFTrim);
                bufferedWriter.close();

                File folder = new File(pathTFTrim);
                File[] listFiles = folder.listFiles();
                List<File> fileList = new ArrayList<>();
                for (File listFile : listFiles) {
                    if (listFile.getName().endsWith(".doc")||listFile.getName().endsWith(".docx")){
                        fileList.add(listFile);
                    }
                }
                ObservableList list = FXCollections.observableArrayList(fileList.stream().map(File::getName).toList());
                LogLV.setItems(list);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
